/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProfesorUI.java
 *
 * Created on Mar 17, 2010, 3:28:43 PM
 */

package edu.fca.ui;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import edu.fca.beans.ProfesorBean;
import edu.fca.ui.search.SearchProfesorUI;
import edu.fca.ui.exceptions.InvalidCodeException;
import edu.fca.ui.exceptions.InvalidLastNameException;
import edu.fca.ui.exceptions.InvalidNameException;
import edu.fca.ui.tools.AlertManager;
import edu.fca.ui.tools.ComponentManager;
import edu.fca.ui.tools.Validations;
import logic.services.ProfesorServices;

/**
 *
 * @author Romms
 */
public class ProfesorUI extends javax.swing.JInternalFrame {

    /** Creates new form ProfesorUI */
    private ProfesorBean profesorBean;

    private enum Action {
        ADD, UPDATE, DELETE
    }

    private Action action;
    private String lastCode;
    
    public ProfesorUI() {
        initComponents();
        System.out.println(this.txtApllM.getParent());
        ComponentManager.enableDisableComponentesIn(this.getContentPane().getComponents(), false);
        startMenuBar();
        profesorBean = new ProfesorBean();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tlbMenuBarra = new javax.swing.JToolBar();
        btnNuevo = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnBorrar = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();
        txtCodigo = new javax.swing.JTextField();
        txtNombre = new javax.swing.JTextField();
        txtApllP = new javax.swing.JTextField();
        txtApllM = new javax.swing.JTextField();
        btnCancel = new javax.swing.JButton();
        btnAcept = new javax.swing.JButton();

        setClosable(true);
        setTitle("Profesor");

        jLabel1.setText("Código:");

        jLabel2.setText("Nombre:");

        jLabel3.setText("Apellido Paterno:");

        jLabel4.setText("Apellido Materno:");

        tlbMenuBarra.setRollover(true);

        btnNuevo.setText("Nuevo");
        btnNuevo.setFocusable(false);
        btnNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnNuevo);

        btnEditar.setText("Editar");
        btnEditar.setFocusable(false);
        btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnEditar);

        btnBorrar.setText("Borrar");
        btnBorrar.setFocusable(false);
        btnBorrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBorrar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnBorrar);

        btnBuscar.setText("Buscar");
        btnBuscar.setFocusable(false);
        btnBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnBuscar);

        btnCancelar.setText("Cancelar");
        btnCancelar.setFocusable(false);
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnCancelar);

        btnAceptar.setText("Aceptar");
        btnAceptar.setFocusable(false);
        btnAceptar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAceptar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        tlbMenuBarra.add(btnAceptar);

        txtCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCodigoFocusLost(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });

        btnCancel.setText("Cancelar");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnAcept.setText("Aceptar");
        btnAcept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tlbMenuBarra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtApllM, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtApllP, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                            .addComponent(txtNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAcept)))
                .addGap(93, 93, 93))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tlbMenuBarra, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtApllP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtApllM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAcept)
                    .addComponent(btnCancel))
                .addContainerGap(53, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        if(this.btnAceptar.isEnabled()){
            int answer=AlertManager.showOkCancelAlert("Registro sin guardar.", "Actualmente está editando un registro, " +
                    "¿Desea borrar la información?");
            if(answer!=0) return;
        }

        ComponentManager.cleanAllInTextFieldsIn(this.getContentPane().getComponents());
        ComponentManager.enableDisableComponentesIn(this.getContentPane().getComponents(), true);
        this.btnAceptar.setEnabled(true);
        this.btnCancelar.setEnabled(true);

        this.btnEditar.setEnabled(false);
        this.btnBorrar.setEnabled(false);
        this.btnBuscar.setEnabled(false);

        this.txtCodigo.requestFocus();

        this.action=Action.ADD;
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void fillProfesorBean(){
        this.profesorBean.setCodigo(this.txtCodigo.getText());
        this.profesorBean.setNombre(this.txtNombre.getText());
        this.profesorBean.setApellidoP(this.txtApllP.getText());
        this.profesorBean.setApellidoM(this.txtApllM.getText());
    }

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        this.accept(action);
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        ComponentManager.cleanAllInTextFieldsIn(this.getContentPane().getComponents());
        ComponentManager.enableDisableComponentesIn(this.getContentPane().getComponents(), false);
        startMenuBar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCodigoFocusLost

    }//GEN-LAST:event_txtCodigoFocusLost

    private void btnAceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptActionPerformed
        this.btnAceptarActionPerformed(evt);
    }//GEN-LAST:event_btnAceptActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.btnCancelarActionPerformed(evt);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        SearchProfesorUI searchProfesorUI=new SearchProfesorUI(null, true);
        searchProfesorUI.setVisible(true);
        searchProfesorUI.dispose();
        this.profesorBean=searchProfesorUI.getSelectedProfesor();
        
        fillProfesorFields(profesorBean);
        this.lastCode=profesorBean.getCodigo();

        this.btnEditar.setEnabled(true);
        this.btnBorrar.setEnabled(true);
        this.btnCancel.setEnabled(true);
        this.btnCancelar.setEnabled(true);
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        ComponentManager.enableDisableComponentesIn(this.getContentPane().getComponents(), true);
        
        this.btnAceptar.setEnabled(true);
        this.btnCancelar.setEnabled(true);

        this.btnEditar.setEnabled(false);
        this.btnBorrar.setEnabled(false);
        this.btnBuscar.setEnabled(false);

        this.txtCodigo.requestFocus();

        this.action=Action.UPDATE;
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed
        this.accept(Action.DELETE);
    }//GEN-LAST:event_btnBorrarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAcept;
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JToolBar tlbMenuBarra;
    private javax.swing.JTextField txtApllM;
    private javax.swing.JTextField txtApllP;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

    private void startMenuBar(){
        btnNuevo.setEnabled(true);
        btnBuscar.setEnabled(true);

        btnEditar.setEnabled(false);
        btnBorrar.setEnabled(false);
        btnCancelar.setEnabled(false);
        btnAceptar.setEnabled(false);
    }

    private void validateData() throws InvalidCodeException, InvalidNameException, InvalidLastNameException{
        if(!Validations.textFieldSizeEqual(this.txtCodigo, 5)){
            this.txtCodigo.requestFocus();
            this.txtCodigo.select(0, this.txtCodigo.getText().length());
            throw new InvalidCodeException("Código de profesor inválido, máximo 5 caracteres.");
        }

        if(this.txtNombre.getText().isEmpty()){
            this.txtNombre.requestFocus();
            throw new InvalidNameException("El nombre no puede ser vacío.");
        }

        if(this.txtApllP.getText().isEmpty()){
            this.txtApllP.requestFocus();
            throw new InvalidLastNameException("El apellido paterno no puede ser vacío.");
        }
    }

    private void fillProfesorFields(ProfesorBean profesorBean){
        this.txtCodigo.setText(profesorBean.getCodigo());
        this.txtNombre.setText(profesorBean.getNombre());
        this.txtApllP.setText(profesorBean.getApellidoP());
        this.txtApllM.setText(profesorBean.getApellidoM());
    }

    private void accept(Action action){

        try {
            validateData();
            fillProfesorBean();

            doAction(action);

            ComponentManager.cleanAllInTextFieldsIn(this.getContentPane().getComponents());
            ComponentManager.enableDisableComponentesIn(this.getContentPane().getComponents(), false);
            startMenuBar();

        }catch (MySQLIntegrityConstraintViolationException ex) {
            AlertManager.showAlert("Código inválido.", "El código "+this.txtCodigo.getText()+" ya existe.");
            this.txtCodigo.select(0, this.txtCodigo.getText().length());
        }catch (InvalidLastNameException ex) {
            AlertManager.showAlert("Apellido paterno inválido.", ex.getExceptionMessage());
        } catch (InvalidNameException ex) {
            AlertManager.showAlert("Nombre inválido.", ex.getExceptionMessage());
        } catch (InvalidCodeException ex) {
            AlertManager.showAlert("Código inválido", ex.getExceptionMessage());
        }
        
    }

    private void doAction(Action action) throws MySQLIntegrityConstraintViolationException{
            switch(action){
            case ADD:
                ProfesorServices.getInstance().addProfesor(profesorBean);
            break;
            case UPDATE:
                ProfesorServices.getInstance().updateProfesor(profesorBean, this.lastCode);
            break;
            case DELETE:
                ProfesorServices.getInstance().deleteProfesor(profesorBean);
            break;

        }
    }

}

